<?php


namespace app\common\cachemodel\zlcr2;


use app\common\model\BaseCache;
use think\Log;
use XznsTools\cache\CacheManage;

class Zlcr2QuestionUserView extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zlcr2_question_user_view';

    protected $cacheModel = 'question_answer.question_view';

    /**
     * 问题蹭看
     * @param array $data
     * @return bool
     */
    public function SaveData(array $data)
    {
        try
        {
            $id = $this->insertGetId($data);
            // 添加至我的问答-蹭看列表
            $this->listDataAdd($data['uid'], [$id => $id]);
            // 添加至问答-蹭看用户列表
            CacheManage::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('view_user', $data['qid'])->listAdd([$data['uid'] => $id], 0, 'view_user');

            return true;
        }
        catch (\Exception $e)
        {
            Log::write('问答 Zlcr2QuestionUserView model => SaveData()异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
            return false;
        }
    }

    /**
     * 修改蹭看(删除,已读)
     * @param $uid
     * @param $id
     * @param $data
     * @return bool
     */
    public function UpdateData($uid, $id, $data)
    {
        try
        {
            $this->where(['id' => $id])->update($data);
            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $id)->setCache($data);
            if (isset($data['is_hide']))
            {
                //我的问答-蹭看列表缓存
                $this->listDataDel($uid, [$id]);
                CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)->setCacheKeyDetail('unread_view', $uid)->delJudge($id, 'unread_view');
            }
            if (isset($data['new_answer']))
            {
                if ($data['new_answer'] === 1)
                {
                    CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)->setCacheKeyDetail('unread_view', $uid)->listAdd([$id => $id], 0, 'unread_view');
                } else
                {
                    CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)->setCacheKeyDetail('unread_view', $uid)->delJudge($id, 'unread_view');
                }
            }

            return true;
        }
        catch (\Exception $e)
        {
            Log::write('问答 Zlcr2QuestionUserView model => UpdateData()异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
            return false;
        }
    }

    /**
     * 获取问答 蹭看用户uids
     * @param string $qid
     * @return array
     * @throws \Exception
     */
    public function getQuestionViewUserIds(string $qid): array
    {
        $resData = CacheManage::getInstance()
            ->setCacheConfig($this->cacheModel)
            ->setCacheKeyDetail('view_user', $qid)
            ->setPage(-1)
            ->getListPageDataIds(function ($isCache = true, $sortType = 'desc') use ($qid)
            {
                try
                {
                    $data = $this->where(['qid' => $qid, 'status' => 1])->column('id', 'uid');
                    $resData = [];
                    foreach ($data as $uid => $createTime)
                    {
                        $resData[$uid] = ['id' => $createTime];
                    }

                    return $resData;
                }
                catch (\Exception $e)
                {
                    return [];
                }
            }, 'id', 0, 'view_user');

        return $resData['data'];
    }

    /**
     * 问题新回复
     * @param string $qid
     * @throws \Exception
     */
    public function questionNewAnswer(string $qid)
    {
        $data = $this->getQuestionViewUserIds($qid);

        if ($data)
        {
            $ids = array_values($data);
            $questionViewInfos = $this->batchGetInfoByIds($ids, ['id', 'uid', 'is_hide']);

            foreach ($questionViewInfos as $id => $item)
            {
                if ($item['is_hide'] === 0)
                {
                    $this->UpdateData($item['uid'], $item['id'], ['new_answer' => 1]);
                }
            }
        }
    }

    public function batchGetInfoByIds($cids, $field = [])
    {
        $resData = parent::batchGetInfoByIds($cids, $field);

        foreach ($resData as $id => $questionItemData)
        {
            $resData[$id] = arrayKeyData2int($questionItemData, ['id', 'uid', 'is_hide', 'new_answer', 'status', 'create_time']);
        }

        return $resData;
    }


    /**
     * 获取问答 用户未读蹭看ids
     * @param string $uid
     * @return array
     * @throws \Exception
     */
    public function getUserUnReadViewIds(string $uid): array
    {
        $resData = CacheManage::getInstance()
            ->setCacheConfig($this->cacheModel)
            ->setCacheKeyDetail('unread_view', $uid)
            ->setPage(-1)
            ->getListPageDataIds(function ($isCache = true, $sortType = 'desc') use ($uid)
            {
                try
                {
                    $data = $this->where(['uid' => $uid, 'new_answer' => 1])->column('id');
                    $resData = [];
                    foreach ($data as $id)
                    {
                        $resData[$id] = ['id' => $id];
                    }

                    return $resData;
                }
                catch (\Exception $e)
                {
                    return [];
                }
            }, 'id', 0, 'unread_view');

        return $resData['data'] ? array_keys($resData['data']) : [];
    }

    /**
     * 批量获取数据
     * @param $ids
     * @param $type
     * @param $sortType
     * @return array|false|string|void
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        try
        {
            if ($ids)
            {
                $model = $this->where('id', 'in', $ids);
            } else
            {
                $model = $this->where(['uid' => $type[0], 'is_hide' => 0]);
            }
            $data = $model->order('id', 'desc')->column('*', 'id');
        }
        catch (\Exception $e)
        {
            $data = [];
        }
        return $data;
    }

    /**
     * 获取用户是否蹭看
     * @param int $uid
     * @param string $qid
     * @return bool
     * @throws \Exception
     */
    public function getQuestionUserIsView(int $uid, string $qid): bool
    {
        $viewUids = $this->getQuestionViewUserIds($qid);
        $viewUids = $viewUids ? array_keys($viewUids) : [];

        return in_array($uid, $viewUids, false) ? true : false;
    }

    /**
     * 获取用户是否蹭看及蹭看数
     * @param int $uid
     * @param string $qid
     * @return array
     * @throws \Exception
     */
    public function getQuestionViewNumAndIsView(int $uid, string $qid): array
    {
        $viewUids = $this->getQuestionViewUserIds($qid);
        $viewUids = $viewUids ? array_keys($viewUids) : [];

        return [
            'is_view' => in_array($uid, $viewUids, false) ? true : false,
            'view_num' => count($viewUids)
        ];
    }
}
